<script setup lang="ts">
import { ref, onMounted } from "vue"

const canvasRef = ref(null)
const canvasPieRef = ref(null)

const drawBar = () => {
  const data = [ 16, 68, 20, 30, 54 ]
  const canvas = canvasRef.value
  const ctx = canvas.getContext('2d')

  ctx.fillStyle = "white"
  ctx.fillRect(0,0,500,500)

  ctx.fillStyle = "blue"
  data.forEach((item, index) => {
    ctx.fillRect(40 + index*100, 460-item*5 , 50, item*5)
  })

  //draw axis lines
  ctx.fillStyle = "black"
  ctx.lineWidth = 2.0
  ctx.beginPath()
  ctx.moveTo(30,10)
  ctx.lineTo(30,460)
  ctx.lineTo(490,460)
  ctx.stroke()

  //draw text and vertical lines
  ctx.fillStyle = "black"
  for(let i=0; i<6; i++) {
    ctx.fillText((5-i)*20 + "",4, i*80+60)
    ctx.beginPath()
    ctx.moveTo(25,i*80+60)
    ctx.lineTo(30,i*80+60)
    ctx.stroke()
  }

  const labels = ["JAN","FEB","MAR","APR","MAY"]
  //draw horiz text
  for(let i=0; i<5; i++) {
    ctx.fillText(labels[i], 50+ i*100, 475)
  }
}

const drawPie = () => {
  const data = [ 100, 68, 20, 30, 100 ]
  const canvas = canvasPieRef.value
  const ctx = canvas.getContext('2d')

  ctx.fillStyle = "white"
  ctx.fillRect(0,0,500,500)

  //a list of colors
  const colors = [ "orange", "green", "blue", "yellow", "teal"]

  //calculate total of all data
  let total = data.reduce((previousValue, currentValue) => (previousValue + currentValue), 0 )

  //draw pie data
  let prevAngle = 0
  data.forEach((item, index) => {
    const fraction = item/total
    //calc starting angle
    const angle = prevAngle + fraction*Math.PI*2

    //draw the pie slice
    ctx.fillStyle = colors[index]

    //fill with a radial gradient
    const grad = ctx.createRadialGradient( 250,250, 10, 250,250, 100)
    grad.addColorStop(0,"white")
    grad.addColorStop(1,colors[index])
    ctx.fillStyle = grad

    //create a path
    ctx.beginPath()
    ctx.moveTo(250,250)
    ctx.arc(250,250, 100, prevAngle, angle, false)
    // ctx.lineTo(250,250)

    //fill it
    ctx.fill()

    //stroke it
    ctx.strokeStyle = "red"
    ctx.stroke()

    //update for next time through the loop
    prevAngle = angle
  })

  //draw centered text
  ctx.fillStyle = "black"
  ctx.font = "bold 24px serif"
  const text = "Sales Data from 2025"
  const metrics = ctx.measureText(text)
  ctx.fillText(text, 250-metrics.width/2, 400)
}

onMounted(() => {
  drawBar()
  drawPie()
})
</script>

<template>
  <canvas width="500" height="500" ref="canvasRef" class="canvas"></canvas>
  <canvas width="500" height="500" ref="canvasPieRef" class="canvas mt-2"></canvas>
</template>

<style scoped lang="scss">
.canvas {
  border: 1px solid black;
}
</style>